package com.fenghongzhang.day0102;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;
import android.widget.EditText;

public class Main2Activity extends AppCompatActivity {
    private EditText edit;

    private  ContentResolver contentResolver;
    private SMSObserver smsObserver;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String s = (String) msg.obj;
            edit.setText(s);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        edit = (EditText) findViewById(R.id.edit);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_SMS},100);
        }

         smsObserver = new SMSObserver(handler, this);

         contentResolver = getContentResolver();
        contentResolver.registerContentObserver(Telephony.Sms.CONTENT_URI,true,smsObserver);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        contentResolver.unregisterContentObserver(smsObserver);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

        }else{
            finish();
        }
    }
}
